<template>
  <el-menu-item index="event-search" @click="setupMapInteraction"> 事件查询 </el-menu-item>
  <el-dialog v-model="dialogVisible" title="事件查询" width="1600px" @closed="resetQuery" draggable>
    <event-info :event-list="filteredEvents" />
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { useMapStore } from '@/stores/mapStore'
import { getAllDataByLayerIndex } from '@/api/mapgis-api/getAllDataByLayerIndex'
import { FeatureToJson } from '@/api'
import EventInfo from './child/EventInfo.vue'

const mapStore = useMapStore()
const dialogVisible = ref(false)
const isDrawingActive = ref(false)
const drawnCircle = ref(null)
const originData = ref([])
const filteredEvents = ref([])
const isDataLoaded = ref(false)

let drawInteraction = null
let tempVectorSource = null

// 初始化原始数据
const initOriginData = async () => {
  try {
    const features = await getAllDataByLayerIndex(2)
    originData.value = FeatureToJson(features).features.map((f) => {
      return {
        ...f.properties.values_,
        coordinates: f.geometry.coordinates[0],
      }
    })
    isDataLoaded.value = true
  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('事件数据加载失败')
    throw error // 向上传递错误
  }
}

// 数据预处理
const processedOriginData = computed(() => {
  return originData.value.map((event) => ({
    ...event,
    事件等级: convertEventLevel(event.事件等级),
  }))
})

const convertEventLevel = (level) => {
  switch (level) {
    case '1':
      return '轻微事故'
    case '2':
      return '一般事故'
    case '3':
      return '重大事故'
    case '4':
      return '特大事故'
    default:
      return '未知等级'
  }
}

// 初始化设置地图交互
const setupMapInteraction = async () => {
  try {
    isDrawingActive.value = !isDrawingActive.value
    if (isDrawingActive.value) {
      await initOriginData() // 等待数据加载
      dialogVisible.value = false
      // 开启绘图模式
      cleanupMap()
      setupTempLayer()
      setupDrawHandler()
    } else {
      // 关闭绘图模式
      cleanupMap()
      resetQuery(true)
    }
  } catch (error) {
    isDrawingActive.value = false
  }
}

// 创建临时绘图图层
const setupTempLayer = () => {
  // 确保只创建一个临时图层
  const existingLayer = mapStore.mapInstance
    .getLayers()
    .getArray()
    .find((layer) => layer.get('name') === 'tempVectorLayer')

  if (!existingLayer) {
    tempVectorSource = new window.ol.source.Vector()
    const layer = new window.ol.layer.Vector({
      name: 'tempVectorLayer',
      source: tempVectorSource,
      zIndex: 9999,
    })
    mapStore.mapInstance.addLayer(layer)
  }
}

// 配置圆形绘制
const setupDrawHandler = () => {
  cleanInteractions()
  drawInteraction = new window.ol.interaction.Draw({
    source: tempVectorSource,
    type: 'Circle',
    style: new window.ol.style.Style({
      stroke: new window.ol.style.Stroke({
        color: 'rgba(0,0,255,0.8)',
        width: 2,
      }),
      fill: new window.ol.style.Fill({
        color: 'rgba(0,0,255,0.1)',
      }),
    }),
  })

  drawInteraction.on('drawend', handleDrawComplete)
  mapStore.mapInstance.addInteraction(drawInteraction)
}

// 处理绘图完成
const handleDrawComplete = async (e) => {
  drawnCircle.value = e.feature
  const circleGeometry = drawnCircle.value.getGeometry()

  filteredEvents.value = processedOriginData.value.filter((event) => {
    return circleGeometry.intersectsCoordinate(event.coordinates)
  })

  tempVectorSource.clear() // 立即清除绘图图形

  // 根据是否找到区域决定是否显示对话框，自动准备下一次绘制
  if (filteredEvents.value.length) {
    dialogVisible.value = true
  } else {
    ElMessage.warning('选定区域无事件数据')
    tempVectorSource.getFeatures().forEach((f) => tempVectorSource.removeFeature(f))
    setupDrawHandler() // 重新激活绘图交互
  }
}

// 清理资源
const resetQuery = (keepDrawing = false) => {
  filteredEvents.value = []
  dialogVisible.value = false
  // 仅当明确要求保持绘图时才不清除
  if (!keepDrawing) {
    if (tempVectorSource) tempVectorSource.clear()
  }
}

// 清理地图资源
const cleanupMap = () => {
  cleanInteractions()
  // 清理临时图层
  const tempLayer = mapStore.mapInstance
    .getLayers()
    .getArray()
    .find((layer) => layer.get('name') === 'tempVectorLayer')

  if (tempLayer) {
    mapStore.mapInstance.removeLayer(tempLayer)
    tempLayer.getSource()?.clear()
    tempLayer.dispose()
  }

  // 清理数据源
  if (tempVectorSource) {
    tempVectorSource.getFeatures().forEach((f) => tempVectorSource.removeFeature(f))
    tempVectorSource.clear()
    tempVectorSource.dispose()
    tempVectorSource = null
  }
}

const cleanInteractions = () => {
  if (drawInteraction) {
    mapStore.mapInstance.removeInteraction(drawInteraction)
    drawInteraction.dispose()
    drawInteraction = null
  }
  // 强制清除可能残留的交互
  const interactions = mapStore.mapInstance.getInteractions().getArray()
  interactions.forEach((interaction) => {
    if (interaction instanceof window.ol.interaction.Draw) {
      mapStore.mapInstance.removeInteraction(interaction)
      interaction.dispose()
    }
  })
}

onBeforeUnmount(() => {
  cleanupMap()
})
</script>

<style lang="scss" scoped></style>
